import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import store from "@/store";
import axios from "axios";
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "home",
    component: () => import("../views/HomeIndex.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/LoginIndex.vue"),

    meta: {
      redirectAlredyLogin: true,
    },
  },
  {
    path: "/signup",
    name: "logsignupin",
    component: () => import("../views/SignUp.vue"),

    meta: {
      redirectAlredyLogin: true,
    },
  },
  {
    path: "/create",
    name: "create",
    component: () => import("../components/CreatePost.vue"),
    meta: {
      requireLogin: true,
    },
  },
  {
    path: "/column/:id",
    name: "column",
    component: () => import("../views/ColumnDetail.vue"),
  },
  {
    path: "/posts/:id",
    name: "posts",
    component: () => import("../views/PostsDetail.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

// router.beforeEach((to, from, next) => {
//   if (to.name !== "login" && store.state.user.isLogin) {
//     next({ name: "login" });
//   } else {
//     next();
//   }
// });

// router.beforeEach((to, from, next) => {
//   if (to.meta.requireLogin && !store.state.user.isLogin) {
//     next({ name: "login" });
//   } else if (to.meta.redirectAlredyLogin && store.state.user.isLogin) {
//     next("/");
//   } else {
//     next();
//   }
// });

router.beforeEach((to, from, next) => {
  const { token, user } = store.state;
  const { redirectAlredyLogin, requiredLogin } = to.meta;
  if (user.isLogin) {
    if (redirectAlredyLogin) {
      next("/");
    } else {
      next();
    }
  } else {
    if (token) {
      axios.defaults.headers.common.Authorization = `Bearer ${token}`;
      store
        .dispatch("fetchCurrentUser")
        .then(() => {
          // 判断是否在登录位置
          if (redirectAlredyLogin) {
            next("/");
          } else {
            next();
          }
        })
        .catch(() => {
         store.commit('loginOut')
          next("/login");
        });
    } else {
      if (requiredLogin) {
        next("/login");
      } else {
        next();
      }
    }
  }
});
export default router;
